package com.hys.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hys.dao.UserMapper;
import com.hys.dto.AuthDTO;
import com.hys.entity.User;
import com.hys.enums.RoleEnum;
import com.hys.exception.ServiceException;
import com.hys.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {


    @Value("${auth.app-id}")
    private String authAppId;

    @Value("${auth.secret}")
    private String authSecret;

    @Value("${auth.url}")
    private String authUrl;

    @Override
    public void doLogin(String username, String password) {
        User user = getByUserName(username);
        if(user == null){
            throw new ServiceException("账号或密码错误");
        }
        if(user.getPassword().equals(password)){
            StpUtil.login(user.getId());
        }else{
            throw new ServiceException("账号或密码错误");
        }
    }

    @Override
    public void doLogin(String appKey) {
        // 根据appKey 去获取用户账号信息
        String account = getUserAccount(appKey);
        log.info("-------------获取当前登录账号信息-----------"+account);
        User user = getByUserAccess(account);
        if(user == null){
            throw new ServiceException("未获取到当前用户对应账号！");
        }
        StpUtil.login(user.getId());
    }

    private String getUserAccount(String appKey)  {

        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("appid",authAppId);
        paramMap.put("secret",authSecret);
        paramMap.put("appkey",appKey);
        // 超时时间设置1分钟
        String resultJson = HttpUtil.get(authUrl, paramMap, 60 * 1000);
        log.info(resultJson);
        ObjectMapper objectMapper = new ObjectMapper();
        AuthDTO authDTO = null;
        try {
            authDTO = objectMapper.readValue(resultJson, AuthDTO.class);
        } catch (JsonProcessingException e) {
            log.error("JSON解析异常", e );
            throw new ServiceException(" JSON解析异常 ");
        }
        return authDTO.getUserAccount();
    }


    @Override
    public User userInfo() {
        Integer loginId = StpUtil.getLoginIdAsInt();
        User user = getById(loginId);
        return user;
    }


    @Override
    public void logout() {
        StpUtil.logout();
    }

    @Override
    public void switchRole(String name) {
        // 退出
        logout();
        // 重新登陆
        QueryWrapper<User> qw = new QueryWrapper<User>();
        qw.eq("name", name);
        User one = getOne(qw);
        if(one == null){
            throw new ServiceException("未查询到当前用户！");
        }
        StpUtil.login(one.getId());
    }


    private User getByUserAccess( String userAccess ){
        QueryWrapper<User> qw = new QueryWrapper<User>();
        qw.eq("user_account", userAccess);
        return getOne(qw);
    }

    private User getByUserName( String userName ){
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.lambda().eq(User::getName, userName);
        return getOne(userQueryWrapper);
    }



}
